<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="链接内容" prop="link">
        <el-input
          v-model="queryParams.link"
          placeholder="请输入链接内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['media:mpQrcodeData:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['media:mpQrcodeData:add']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mpQrcodeDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="链接内容" align="center" prop="link" />
<!--      <el-table-column label="链接内容" align="center" prop="link" >-->
<!--        <template slot-scope="scope">-->
<!--          <div style="margin-left: 30px" :id="'qrcode' + scope.row.id"></div> -->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="二维码更新时间" align="center" prop="qrCodeUpdateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.qrCodeUpdateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否使用" align="center" prop="isUse" >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.isUse === 0">未使用</el-tag>
          <el-tag type="danger" v-if="scope.row.isUse === 1">已使用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" >
        <template slot-scope="scope">
        <el-input  v-model="scope.row.remark"></el-input>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="saveData(scope.row)"
          >保存</el-button>
          <el-button
            size="mini"
            type="text"
            @click="createQR(scope.row)"
          >生成二维码</el-button>

<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['media:mpQrcodeData:remove']"-->
<!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

<!--    二维码弹框 -->
    <el-dialog title="请扫码入群" :visible.sync="qrcodeVisible"  :before-close="handleDialogClose" width="300px" append-to-body>
      <div style="margin-left: 30px;margin-bottom: 20px">
        <div  id="qrcode" ref="qrcode"></div>
      </div>
    </el-dialog>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改微信群二维码数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="链接内容" prop="link">
          <el-input v-model="form.link" placeholder="请输入链接内容" />
        </el-form-item>
<!--        <el-form-item label="二维码更新时间" prop="qrCodeUpdateTime">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.qrCodeUpdateTime"-->
<!--            type="datetime"-->
<!--            value-format="yyyy-MM-dd HH:mm:ss"-->
<!--            placeholder="请选择二维码更新时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMpQrcodeData, getMpQrcodeData, delMpQrcodeData, addMpQrcodeData, updateMpQrcodeData,setLookStatus } from "@/api/media/mpQrcodeData";
import QRCode from 'qrcodejs2'
export default {
  name: "MpQrcodeData",
  data() {
    return {
      // 按钮loading
      qrcode:'',
      buttonLoading: false,
      //二维码弹框
      qrcodeVisible:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      linkContent:'',
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 微信群二维码数据表格数据
      mpQrcodeDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        userId: undefined,
        link: undefined,
        qrCodeUpdateTime: undefined,
        linkId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        link: [
          { required: true, message: "链接内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    const linkId = this.$route.params && this.$route.params.id;
    this.queryParams.linkId = linkId
    this.getList();
  },
  methods: {
    /** 查询微信群二维码数据列表 */
    getList() {
      let that = this;
      this.loading = true;
      listMpQrcodeData(this.queryParams).then(response => {
        this.mpQrcodeDataList = response.rows;
        this.total = response.total;
      });
      // setTimeout(()=>{
      //   that.mpQrcodeDataList.forEach(item => {
      //     console.log(item.id)
      //     let qrCodeImage = new QRCode(document.getElementById("qrcode" + item.id), {
      //       text: item.link,
      //       width: 128,
      //       height: 128,
      //       colorDark: "#000000",
      //       colorLight: "#ffffff",
      //       correctLevel: QRCode.CorrectLevel.L
      //     });
      //   });
      // },2000)
      this.loading = false;
    },


    /**
     *  二维码展示回调
     * @param row
     */
    setLookStatusClick(row){
      setLookStatus(row.id).then((res)=>{
        console.log(res)
      })
    },


    /**
     * 保存数据
     * @param row
     */
    saveData(row){
      this.loading = true;
      updateMpQrcodeData(row).then(response => {
        this.$modal.msgSuccess("保存成功！");
        this.getList();
      }).finally(() => {
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        userId: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        link: undefined,
        qrCodeUpdateTime: undefined,
        linkId: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /**
     * 创建二维码
     */
    createQR(row){
      this.linkContent =  row.link
      this.qrcodeVisible = true;
      setTimeout(()=>{
        this.createQRCode()
        this.setLookStatusClick(row)
      },100)
    },


    /**
     * 创建二维码
     * @param row
     */
    createQRCode(){
      this.$refs['qrcode'].innerHTML = ''
      this.qrcode = new QRCode('qrcode', {
        text: this.linkContent,
        width: 200, //图像宽度
        height: 200, //图像高度
        colorDark : "#000000", //前景色
        colorLight : "#ffffff", //背景色
        typeNumber:4,
        correctLevel : QRCode.CorrectLevel.H //容错级别 容错级别有：（1）QRCode.CorrectLevel.L （2）QRCode.CorrectLevel.M （3）QRCode.CorrectLevel.Q （4）QRCode.CorrectLevel.H
      })
    },

    /**
     * 创建二维码
     * @param row
     */
    // createQRCode(row){
    //   console.log(row)
    //   this.$refs['qrcode' + row.id].innerHTML = ''
    //   this.qrcode = new QRCode('qrcode'+row.id, {
    //     text: row.linkContent,
    //     width: 200, //图像宽度
    //     height: 200, //图像高度
    //     colorDark : "#000000", //前景色
    //     colorLight : "#ffffff", //背景色
    //     typeNumber:4,
    //     correctLevel : QRCode.CorrectLevel.H //容错级别 容错级别有：（1）QRCode.CorrectLevel.L （2）QRCode.CorrectLevel.M （3）QRCode.CorrectLevel.Q （4）QRCode.CorrectLevel.H
    //   })
    // },

    handleDialogClose(){
      this.getList();
      this.qrcodeVisible = false
      this.$refs['qrcode'].innerHTML = ''
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加微信群二维码数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMpQrcodeData(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改微信群二维码数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMpQrcodeData(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMpQrcodeData(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除微信群二维码数据编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMpQrcodeData(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('media/mpQrcodeData/export', {
        ...this.queryParams
      }, `mpQrcodeData_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
